/*
Copyright SecureKey Technologies Inc. All Rights Reserved.

SPDX-License-Identifier: Apache-2.0
*/

package discovery

import (
	"git.cloud.inspur.com/ichain/ichain-sdk-go/pkg/common/filter"
	"git.cloud.inspur.com/ichain/ichain-sdk-go/pkg/common/logging"
	contextAPI "git.cloud.inspur.com/ichain/ichain-sdk-go/pkg/providers/context"
	"git.cloud.inspur.com/ichain/ichain-sdk-go/pkg/providers/ichain"
	"github.com/pkg/errors"
)

var logger = logging.NewLogger("ichainsdk/client")

type LocalProvider struct {
	config   ichain.EndpointConfig
	provider ichain.IChainProvider
}

func NewLocalProvider(config ichain.EndpointConfig) (*LocalProvider, error) {
	return &LocalProvider{config: config}, nil
}

// Initialize
// @Description: 初始化
func (dp *LocalProvider) Initialize(pvdr contextAPI.Providers) error {
	dp.provider = pvdr.IChainProvider()
	return nil
}

// CreateLocalDiscoveryService 初始化一个过滤非相同iam的节点
func (dp *LocalProvider) CreateLocalDiscoveryService(iamID string) (ichain.DiscoveryService, error) {
	netInodes := dp.config.NetworkInodes()

	logger.Debugf("Found %d inodes", len(netInodes))

	// todo 高版本后支持动态获取

	srv, err := newStaticService(dp.provider, netInodes)
	if err != nil {
		return nil, errors.WithMessage(err, "new local discover fail")
	}

	return NewFilterDiscovery(srv, filter.NewIAMFilter(iamID)), nil
}
